import axios from 'axios';
import { getItem } from '@/utils/storage';
import { ToastError, Toastloading } from './public';
import { userStore } from '@/pinia/modules/user';
// const useUserStore = userStore();
// const { FedLogOut } = useUserStore;
//创建axios的一个实例
const baseURL = import.meta.env.VITE_HTTP;
const instance = axios.create({
    headers: {
        'Content-Type': 'application/json'
    },
    baseURL,//接口统一域名
    timeout: 30000
})
//------------------- 一、请求拦截器
instance.interceptors.request.use(function (config: any) {
    if (getItem('SET_TOKEN')) {
        config.headers['X-Token'] = getItem('SET_TOKEN');
    }
    let { params={}, method='get' } = config
    // get请求剔除空参数处理 接口没默认值 参数传null 则赋空传递
    if(method == 'get') {
        for(let i in params) {
            if(typeof(params[i]) == 'string' && params[i] == '') {
                delete params[i]
            } else if(params[i] == null) {
                params[i] = ''
            }
        }
        config.params = params
    }
    return config;
}, function (error: any) {
    return Promise.reject(error);
});

//----------------- 二、响应拦截器
instance.interceptors.response.use(function (response: any) {
    const { message, code, data} = response.data
    if(code == 50014) {
        userStore().FedLogOut()
        return Promise.reject();
    }
    if(code != 20000 && code != 0) {
        const { msg='' } = data || {msg:''}
        ToastError(msg?msg:message)
        Toastloading().close();
        return Promise.reject();
    }else {
        if(data == null) {
            console.error('data error null')
            return Promise.resolve({data:{}});
        }
        return Promise.resolve({...response.data});
    }

}, function (error: any) {
    // 对响应错误做点什么
    ToastError('当前网络异常，请稍后再试')
    Toastloading().close();
    return Promise.reject(error);
});

export default instance
